﻿using AgencyManagerSystem.AsmType;
using AgencyManagerSystem.Common;
using AgencyManagerSystem.DataFetcher;
using AgencyManagerSystem.DataUpdater;
using AgencyManagerSystem.Model;
using System;
using System.Collections.Generic;

namespace AgencyManagerSystem.Core
{
    public abstract class MainDetailManager<TMain,TDetail>  where TMain : DBModel where TDetail:DBModel
    {
        protected string TranCode;
        public MainDetailManager()
        {
            this.mainDetailUpdater = InjectionMainDetailUpdater();
        }
        protected MainDetailUpdater<TMain, TDetail> mainDetailUpdater;
        protected abstract MainDetailUpdater<TMain, TDetail> InjectionMainDetailUpdater();
        public virtual AsmMainDetail<TMain, TDetail> Set(TMain main, IEnumerable<TDetail> detail)
        {
            string message;
            int result = mainDetailUpdater.BulkUpdate(main, detail, out message);
            if (result == 0)
            {
                DBHelper.Commit( false);
                return new AsmMainDetail<TMain, TDetail>() { Message = message, Result = AmsCode.InnError };
            }
            else
            {
                return new AsmMainDetail<TMain, TDetail>() { Message = "操作成功", Result = AmsCode.Succ, Data = main, Detail = detail };
            }
        }
        public virtual AsmObject<bool> Delete(TMain main)
        {
            string message;
            bool result = mainDetailUpdater.BulkDeleting(main.AutoId, out message);
            if (!result)
            {
                DBHelper.Commit( false);
                return new AsmObject<bool>() { Message = message, Result = AmsCode.InnError, Data = false };
            }
            else
            {
                return new AsmObject<bool>() { Message = "操作成功", Result = AmsCode.Succ, Data = true };
            }
        }
        public virtual AsmObject<bool> Approve(TMain main)
        {
            string message;
            bool result = mainDetailUpdater.BulkApprove(main.AutoId, ApproveCode.Approved ,out message);
            if (!result)
            {
                DBHelper.Commit( false);
                return new AsmObject<bool>() { Message = message, Result = AmsCode.InnError, Data = false };
            }
            else
            {
                return new AsmObject<bool>() { Message = "操作成功", Result = AmsCode.Succ, Data = true };
            }
        }

        public virtual AsmObject<bool> UnApprove(TMain main)
        {
            string message;
            bool result = mainDetailUpdater.BulkApprove(main.AutoId, ApproveCode.Normal, out message);
            if (!result)
            {
                DBHelper.Commit( false);
                return new AsmObject<bool>() { Message = message, Result = AmsCode.InnError, Data = false };
            }
            else
            {
                return new AsmObject<bool>() { Message = "操作成功", Result = AmsCode.Succ, Data = true };
            }
        }
    }
}
